﻿using Newtonsoft.Json;
using ProjBackEnd.Common;
using ProjBackEnd.Common.Helper;
using ProjBackEnd.Models;
using ProjBackEnd.Models.AppModel.AppApproveModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjBackEnd.Service
{
    public sealed partial class AppApproveService
    { 
        /// <summary>
        /// 结算单拒绝
        /// </summary> 
        public string RefuseFNBill(RefuseYWBillModel model)
        {
            string conn = Function.GetConnectionString();

            ResultModel resultObj = new ResultModel();

            using (SqlConnection connYard = new SqlConnection(conn))
            {
                connYard.Open();
                SqlTransaction tran = connYard.BeginTransaction();

                SqlCommand cmdYard = new SqlCommand();
                cmdYard.Connection = connYard;
                cmdYard.Transaction = tran;

                try
                {
                    if (model == null)
                    {
                        throw new Exception("对象为空！");
                    }

                    if (string.IsNullOrEmpty(model.billid))
                    {
                        throw new Exception("billid不能为空！");
                    }

                    if (string.IsNullOrEmpty(model.fnid))
                    {
                        throw new Exception("fnid不能为空！");
                    }

                    if (string.IsNullOrEmpty(model.memberid))
                    {
                        throw new Exception("userid不能为空！");
                    }

                    DateTime dtnow = DateTime.Now;

                    //原因
                    string remark = string.IsNullOrEmpty(model.remark) ? "" : model.remark.Trim();

                    string billid = model.billid.Trim();
                    string fnid = model.fnid.Trim();
                    string memberid = model.memberid.Trim();

                    string sql = $@"select * from FIN_FEENOTICE where FIN_FEENOTICE.fnid = {fnid}";
                    DataSet dsInfo = SqlHelper.GetDataSet(sql, conn);
                    if (dsInfo.Tables[0].Rows.Count < 1)
                    {
                        throw new Exception($"没有找到审批单！fnid：{fnid}");
                    }
                     
                    //取当前的审批信息
                      sql = $@"select top 1 *
                                    from FIN_REVFLOW
                                    where (FIN_REVFLOW.reviewer1 = '{memberid}' and isnull(FIN_REVFLOW.revlb1,'') <> 'Y' or FIN_REVFLOW.reviewer2 = '{memberid}' and isnull(FIN_REVFLOW.revlb2,'') <> 'Y')
                                     and FIN_REVFLOW.applyid = {fnid}
                                     and FIN_REVFLOW.applytp = 'FN'
                                    order by sortval asc";

                    DataSet dsFlow = SqlHelper.GetDataSet(sql, conn);
                    if (dsFlow.Tables[0].Rows.Count < 1)
                        throw new Exception($"没有找到待审批流程！applyid：{fnid}");

                    sql = $@"select * from FIN_BILLTB where billid = {billid}";
                    DataSet dsBilltb = SqlHelper.GetDataSet(sql, conn);
                    if (dsBilltb.Tables[0].Rows.Count < 1)
                        throw new Exception($"没有找到账单信息！billid：{billid}");

                    //应付
                    decimal amt_pay = dsBilltb.Tables[0].Rows[0]["amt_pay"] == DBNull.Value ? 0 :
                        Convert.ToDecimal(dsBilltb.Tables[0].Rows[0]["amt_pay"]);

                    //应收
                    decimal amt_rec = dsBilltb.Tables[0].Rows[0]["amt_rec"] == DBNull.Value ? 0 :
                        Convert.ToDecimal(dsBilltb.Tables[0].Rows[0]["amt_rec"]);

                    //结算金额
                    decimal amt_settle = dsInfo.Tables[0].Rows[0]["amt_settle"] == DBNull.Value ? 0 :
                        Convert.ToDecimal(dsInfo.Tables[0].Rows[0]["amt_settle"]);

                    if (amt_pay + amt_rec == amt_settle)
                    {
                        //审批完成
                        //FIN_BILLTB.pid置为3
                        sql = $@"update FIN_BILLTB set pid = '3' where billid = {billid}";
                        cmdYard.CommandType = CommandType.Text;
                        cmdYard.CommandText = sql;
                        cmdYard.ExecuteNonQuery();
                    }
                    else
                    {
                        //审批中
                        //FIN_BILLTB.pid置为4
                        sql = $@"update FIN_BILLTB set pid = '4' where billid = {billid}";
                        cmdYard.CommandType = CommandType.Text;
                        cmdYard.CommandText = sql;
                        cmdYard.ExecuteNonQuery();
                    }

 
                    string sortval = dsFlow.Tables[0].Rows[0]["sortval"].ToString().Trim();
                    string applytp = dsFlow.Tables[0].Rows[0]["applytp"].ToString().Trim();



                    //FIN_FEENOTICE
                    sql = $@"update FIN_FEENOTICE set pid = '0' where fnid = {fnid}";
                    cmdYard.CommandType = CommandType.Text;
                    cmdYard.CommandText = sql;
                    int rows = cmdYard.ExecuteNonQuery();

                    //删掉流程  FIN_REVFLOW
                    sql = $@"delete from FIN_REVFLOW where FIN_REVFLOW.applyid = {fnid} and FIN_REVFLOW.applytp = 'FN'";
                    cmdYard.CommandType = CommandType.Text;
                    cmdYard.CommandText = sql;
                    rows = cmdYard.ExecuteNonQuery();

                    //写日志 FIN_REVDENYTB
                    sql = $@"insert into FIN_REVDENYTB(applyid,applytp,reviewer,advice,createdt)
                                        values({fnid},'FN','{memberid}','{remark}','{dtnow.ToString()}')";
                    cmdYard.CommandType = CommandType.Text;
                    cmdYard.CommandText = sql;
                    rows = cmdYard.ExecuteNonQuery();

                    //提交 
                    tran.Commit();

                    resultObj.code = "0";
                    resultObj.message = "";
                    return JsonConvert.SerializeObject(resultObj);
                }
                catch (Exception ex)
                {
                    //回滚
                    tran.Rollback();

                    resultObj.code = "99";
                    resultObj.message = ex.Message;
                    return JsonConvert.SerializeObject(resultObj);
                }
                finally
                {
                    //释放内存
                    connYard.Close();
                    connYard.Dispose();
                    cmdYard.Dispose();
                }
            }
        }



        /// <summary>
        /// 结算单审批通过
        /// </summary> 
        public string ApproveFNBill(RefuseYWBillModel model)
        {
            string conn = Function.GetConnectionString();

            ResultModel resultObj = new ResultModel();

            try
            {
                if (model == null)
                {
                    throw new Exception("对象为空！");
                }

                if (string.IsNullOrEmpty(model.billid))
                {
                    throw new Exception("billid不能为空！");
                }

                if (string.IsNullOrEmpty(model.memberid))
                {
                    throw new Exception("userid不能为空！");
                }

                if (string.IsNullOrEmpty(model.fnid))
                {
                    throw new Exception("fnid不能为空！");
                }

                DateTime dtnow = DateTime.Now;
                  
                string billid = model.billid.Trim();
                string fnid = model.fnid.Trim(); 
                string memberid = model.memberid.Trim();

                //取当前的审批信息
                string sql = $@"select top 1 *
                                    from FIN_REVFLOW
                                    where (FIN_REVFLOW.reviewer1 = '{memberid}' and isnull(FIN_REVFLOW.revlb1,'') <> 'Y' or FIN_REVFLOW.reviewer2 = '{memberid}' and isnull(FIN_REVFLOW.revlb2,'') <> 'Y')
                                     and FIN_REVFLOW.applyid = {fnid}
                                     and FIN_REVFLOW.applytp = 'FN'
                                    order by sortval asc";

                DataSet dsFlow = SqlHelper.GetDataSet(sql, conn);
                if (dsFlow.Tables[0].Rows.Count < 1)
                    throw new Exception("没有找到待审批信息！");

                string sortval = dsFlow.Tables[0].Rows[0]["sortval"].ToString().Trim();
                string revtp = dsFlow.Tables[0].Rows[0]["revtp"].ToString().Trim();

                //审批
                if (dsFlow.Tables[0].Rows[0]["reviewer1"].ToString().Trim() == memberid)
                {
                    sql = $@"update FIN_REVFLOW set revlb1 = 'Y',revdt1 = '{dtnow.ToString()}'
                            where sortval = {sortval} and applyid = {fnid} and applytp = 'FN'";
                    SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                }
                else
                {
                    sql = $@"update FIN_REVFLOW set revlb2 = 'Y',revdt2 = '{dtnow.ToString()}'
                            where sortval = {sortval} and applyid = {fnid} and applytp = 'FN'";
                    SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                }

                //找到下一级流程
                sql = $@"select top 1 *
                                    from FIN_REVFLOW
                                    where FIN_REVFLOW.sortval > {sortval}
                                     and FIN_REVFLOW.applyid = {fnid}
                                     and FIN_REVFLOW.applytp = 'FN'
                                    order by sortval asc";
                dsFlow = SqlHelper.GetDataSetSchema(sql, "FIN_REVFLOW", conn);


                bool approvelb = false;

                if (revtp == "0")
                {
                    //选审
                    if (dsFlow.Tables[0].Rows.Count < 1)
                    {
                        //没有下一级流程了，审批通过
                        sql = $@"update FIN_FEENOTICE set pid = '3' where fnid = {fnid}";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);

                        approvelb = true;
                    }
                    else
                    {
                        //开启下一级流程
                        if (dsFlow.Tables[0].Rows[0]["reviewer1"].ToString().Trim() != "")
                        {
                            dsFlow.Tables[0].Rows[0]["revlb1"] = "N";
                        }

                        if (dsFlow.Tables[0].Rows[0]["reviewer2"].ToString().Trim() != "")
                        {
                            dsFlow.Tables[0].Rows[0]["revlb2"] = "N";
                        }
                        if (dsFlow.HasChanges())
                        {
                            SqlHelper.UpdateDataSet(dsFlow, conn);
                        }
                    }
                }
                else
                {
                    //共审

                    //取当前流程的最新状态
                    sql = $@"select top 1 *
                                        from FIN_REVFLOW
                                        where FIN_REVFLOW.sortval = {sortval}
                                         and FIN_REVFLOW.applyid = {fnid}
                                         and FIN_REVFLOW.applytp = 'FN'";
                    DataSet dsCurrentFlow = SqlHelper.GetDataSet(sql, conn);

                    if (dsCurrentFlow.Tables[0].Rows[0]["revlb1"].ToString().Trim() == "Y" &&
                       dsCurrentFlow.Tables[0].Rows[0]["revlb2"].ToString().Trim() == "Y")
                    {
                        //当前级审批通过

                        if (dsFlow.Tables[0].Rows.Count < 1)
                        {
                            //没有下一级流程了，审批通过
                            sql = $@"update FIN_FEENOTICE set pid = '3' where fnid = {fnid}";
                            SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);

                            approvelb = true;
                        }
                        else
                        {
                            //开启下一级流程
                            if (dsFlow.Tables[0].Rows[0]["reviewer1"].ToString().Trim() != "")
                            {
                                dsFlow.Tables[0].Rows[0]["revlb1"] = "N";
                            }

                            if (dsFlow.Tables[0].Rows[0]["reviewer2"].ToString().Trim() != "")
                            {
                                dsFlow.Tables[0].Rows[0]["revlb2"] = "N";
                            }
                            if (dsFlow.HasChanges())
                            {
                                SqlHelper.UpdateDataSet(dsFlow, conn);
                            }
                        }
                    } 
                }


                //如果当前结算单是审批完成的状态，则需对其所属账单的pid做出相应的调整
                if (approvelb)
                {
                    sql = $@"select * from FIN_BILLTB where billid = {billid}";
                    DataSet dsBilltb = SqlHelper.GetDataSet(sql, conn);
                    if (dsBilltb.Tables[0].Rows.Count < 1)
                        throw new Exception($"没有找到账单信息！billid：{billid}");

                    //应付
                    decimal amt_pay = dsBilltb.Tables[0].Rows[0]["amt_pay"] == DBNull.Value ? 0 :
                        Convert.ToDecimal(dsBilltb.Tables[0].Rows[0]["amt_pay"]);

                    //应收
                    decimal amt_rec = dsBilltb.Tables[0].Rows[0]["amt_rec"] == DBNull.Value ? 0 :
                        Convert.ToDecimal(dsBilltb.Tables[0].Rows[0]["amt_rec"]);

                    sql = $@"select * from FIN_FEENOTICE where fnid = {fnid}";
                    DataSet dsFeenotice = SqlHelper.GetDataSet(sql, conn);
                    if (dsFeenotice.Tables[0].Rows.Count < 1)
                        throw new Exception($"没有找到结算单信息！fnid：{fnid}");

                    //结算金额
                    decimal amt_settle = dsFeenotice.Tables[0].Rows[0]["amt_settle"] == DBNull.Value ? 0 :
                        Convert.ToDecimal(dsFeenotice.Tables[0].Rows[0]["amt_settle"]);

                    if (amt_pay + amt_rec == amt_settle)
                    {
                        //审批完成
                        //FIN_BILLTB.pid置为5
                        sql = $@"update FIN_BILLTB set pid = '5' where billid = {billid}";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                    else
                    {
                        //审批中
                        //FIN_BILLTB.pid置为4
                        sql = $@"update FIN_BILLTB set pid = '4' where billid = {billid}";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }

                     
                }


                resultObj.code = "0";
                resultObj.message = "";
                return JsonConvert.SerializeObject(resultObj);
            }
            catch (Exception ex)
            {

                resultObj.code = "99";
                resultObj.message = ex.Message;
                return JsonConvert.SerializeObject(resultObj);
            }
        }

    }
}
